package com.atguigu.spzx.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.consts.SpzxConsts;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局登录状态校验
 *      逻辑： 访问路径满足/api/~~/auth/~~ 的需要校验登录状态
 *              获取请求头中的token
 *              再判断redis中是否有token这个键
 */
@Component
public class SpzxGlobalAuthFilter implements GlobalFilter {
    AntPathMatcher matcher = new AntPathMatcher();
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        boolean match = matcher.match("/api/**/auth/**", path);
        if(!match){
            //访问的路径不需要验证登录状态  直接放行
            return chain.filter(exchange);
        }
        //需要鉴权：
        String token = request.getHeaders().getFirst("token");
        Boolean isLogin = false;
        //到redis中判断token是否存在登录状态
        if(!StringUtils.isEmpty(token)){
            isLogin = redisTemplate.hasKey(SpzxConsts.SPZX_USER_LOGIN_PREFIX + token);
        }
        if(isLogin){
            //表示已登录：放行
            return chain.filter(exchange);
        }
        //访问的路径需要鉴权，但是没有携带token 或者token失效：拒绝请求 响应一个需要登录的Result对象
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", ResultCodeEnum.LOGIN_STATUS_ERROR.getCode());
        jsonObject.put("message", ResultCodeEnum.LOGIN_STATUS_ERROR.getMesssage());
        String rJson = jsonObject.toJSONString();
        Mono<DataBuffer> mono = Mono.just(response.bufferFactory().wrap(rJson.getBytes()));
        return response.writeWith(mono);
    }
}
